/*************************************************************************************
 *
 *  Revolution Engine
 *  Copyright (C) 2009 Felipe Apablaza
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; either
 *  version 2.1 of the License, or (at your option) any later version.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 ************************************************************************************/


#include <RevEng/IThread.hpp>
#include "ThreadWin32.hpp"

namespace RevEng
{
	DWORD WINAPI RunThreadCall(LPVOID lpParam) 
	{ 
		ThreadCall *Call; 
		DWORD Result;
		
		Call = (ThreadCall *) lpParam;
		Result = (DWORD) Call->Threaded->Run( Call->Param );

		return Result;
	} 

	
	ThreadWin32::ThreadWin32() : m_hThreadID(0), m_hThread(NULL), m_eStatus(REVENG_THREAD_READY)
	{
		//Crear el hilo en estado suspendido
		m_hThread = ::CreateThread(NULL, 0, RunThreadCall, &m_tcCall, CREATE_SUSPENDED, &m_hThreadID);

		m_tcCall.Param = NULL;
	}

	ThreadWin32::~ThreadWin32()
	{
		//Cerramos el handle.
		::CloseHandle(m_hThread);
	}


	void ThreadWin32::Start(void* Param)
	{
		if (m_tcCall.Threaded != NULL)
		{
			m_tcCall.Param = Param;
			m_eStatus = REVENG_THREAD_RUNNING;
			::ResumeThread( m_hThread );
		}
	}


	//Espera a que este thread termine su ejecucion
	void ThreadWin32::Wait()
	{
		::WaitForSingleObject(m_hThread, INFINITE);
		m_eStatus = REVENG_THREAD_READY;
	}


	void ThreadWin32::Abort()
	{
		::TerminateThread(m_hThread, 1);
		m_eStatus = REVENG_THREAD_READY;
	}


	void ThreadWin32::SetThreaded(IThreaded *Threaded)
	{
		m_tcCall.Threaded = Threaded;
	}


	Enum ThreadWin32::GetStatus() const
	{
		return m_eStatus;
	}
	
	Int32 ThreadWin32::GetExitCode() const
	{
		DWORD RetVal;
	    
		if (::GetExitCodeThread(m_hThread, &RetVal))
			return (Int32)RetVal;
		else
			return -1;
	}

	void IThread::Sleep(double Secs)
	{
		::Sleep( static_cast<DWORD>(Secs * 1000.0) );
	}


	void IThread::Yield()
	{
		::SwitchToThread();
	}
}
